<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>汉字自由联想心理分析 - 测试说明</title>
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- 自定义配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4A6FA5',
            secondary: '#6B8EAF',
            accent: '#E76F51',
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .btn-hover {
        background-color: #3A5A85;
        transform: translateY(-2px);
      }
      .upload-hover {
        border-color: #4A6FA5;
        background-color: #f0f4f8;
      }
      .fade-in {
        animation: fadeIn 0.5s ease-in;
      }
      @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
      }
    }
  </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
  <div class="container mx-auto px-4 py-8 max-w-md flex-grow">
    <!-- 返回按钮 -->
    <div class="mb-8">
      <button id="back-button" class="text-primary hover:text-primary/80 transition-colors">
        <i class="fa fa-arrow-left mr-2"></i>返回
      </button>
    </div>

    <!-- 页面标题 -->
    <h1 class="text-2xl font-bold text-center text-primary mb-8">汉字自由联想心理分析</h1>

    <!-- 欢迎语 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-8">
      <p class="text-gray-700 leading-relaxed">
        欢迎用汉字探索自己的内心世界，接下来，系统将使用你自由联想的30个汉字，详细反应你的内心关注与期望。
      </p>
    </div>

    <!-- 测评准备 -->
    <div class="mb-8">
      <h2 class="text-xl font-bold text-accent mb-4">测评准备：</h2>
      <div class="bg-white rounded-xl shadow-sm p-6">
        <p class="text-gray-700 leading-relaxed">
          请准备好纸笔、安静的环境，选择舒适的坐姿，进行缓慢的深呼吸，当你感觉自己头脑放松而专注时，可以开始试着在脑海中浮现一个汉字（共想30个汉字），一旦想到，立刻写下来。
        </p>
      </div>
    </div>

    <!-- 注意事项 -->
    <div class="mb-12">
      <h2 class="text-xl font-bold text-accent mb-4">注意事项：</h2>
      <div class="bg-white rounded-xl shadow-sm p-6">
        <ol class="list-decimal list-inside space-y-3 text-gray-700">
          <li>每次只想一个汉字，直到写满30个汉字。</li>
          <li>请尽量不受当前环境影响，例如不要看到书本写下"书"字，听到鸣笛而写下"滴"字。</li>
          <li>如果想到了词或句，选择一个字写下来。</li>
          <li>不要回头看写过的字。</li>
          <li>字迹要清晰，以便AI识别。</li>
        </ol>
      </div>
    </div>

    <!-- 照片上传区域 -->
    <div class="mb-8">
      <h2 class="text-xl font-bold text-accent mb-4">请拍照上传你书写的30个汉字</h2>
      <div class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center transition-all hover:upload-hover cursor-pointer" id="upload-area">
        <i class="fa fa-camera text-4xl text-gray-400 mb-4"></i>
        <p class="text-gray-600 mb-2">点击或拖拽文件到此处上传</p>
        <p class="text-xs text-gray-500">支持 JPG、PNG 格式，文件大小不超过 10MB</p>
        <input type="file" id="file-input" class="hidden" accept="image/*">
      </div>
      <div id="image-preview" class="hidden mt-4 fade-in">
        <img id="preview-img" class="max-w-full h-auto rounded-lg">
        <button id="remove-image" class="mt-2 text-sm text-accent hover:underline">移除图片</button>
      </div>
    </div>

    <!-- 提交按钮 -->
    <button 
      id="submit-button" 
      class="w-full bg-primary text-white py-4 rounded-lg font-medium transition-all hover:btn-hover disabled:opacity-50 disabled:cursor-not-allowed"
      disabled
    >
      上传照片，提交分析
    </button>
  </div>

  <!-- 加载动画 (默认隐藏) -->
  <div id="loading-overlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden fade-in">
    <div class="bg-white p-6 rounded-xl text-center">
      <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent mb-4"></div>
      <p class="text-gray-700">正在识别图片中的汉字，请稍候...</p>
    </div>
  </div>

  <!-- JavaScript -->
  <script>
    // 元素选择器
    const backButton = document.getElementById('back-button');
    const uploadArea = document.getElementById('upload-area');
    const fileInput = document.getElementById('file-input');
    const imagePreview = document.getElementById('image-preview');
    const previewImg = document.getElementById('preview-img');
    const removeImage = document.getElementById('remove-image');
    const submitButton = document.getElementById('submit-button');
    const loadingOverlay = document.getElementById('loading-overlay');
    
    // Coze工作流配置 - 根据用户提供的格式更新
    const COZE_API_KEY = 'pat_SlLREElBSRnO5GVL8nopClZaMqoyMScm0idEOg6e7X6v1lM7mSG9O3HF5zOP8qH1'; // 用户配置的Coze API密钥
    const COZE_WORKFLOW_ENDPOINT = 'https://api.coze.cn/v1/workflow/run'; // Coze工作流API端点 - 使用v1版本

    // 返回按钮点击事件
    backButton.addEventListener('click', function() {
      window.location.href = 'gender-age.html';
    });

    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', function() {
      fileInput.click();
    });

    // 处理文件选择
    fileInput.addEventListener('change', function(e) {
      if (e.target.files && e.target.files[0]) {
        const file = e.target.files[0];
        
        // 验证文件类型
        if (!file.type.match('image/jpeg') && !file.type.match('image/png')) {
          alert('请上传JPG或PNG格式的图片');
          return;
        }
        
        // 验证文件大小（10MB）
        if (file.size > 10 * 1024 * 1024) {
          alert('图片大小不能超过10MB');
          return;
        }
        
        // 显示图片预览
        const reader = new FileReader();
        reader.onload = function(event) {
          previewImg.src = event.target.result;
          imagePreview.classList.remove('hidden');
          submitButton.disabled = false;
        };
        reader.readAsDataURL(file);
      }
    });

    // 移除图片
    removeImage.addEventListener('click', function() {
      fileInput.value = '';
      imagePreview.classList.add('hidden');
      submitButton.disabled = true;
    });

    // 拖拽上传功能
    uploadArea.addEventListener('dragover', function(e) {
      e.preventDefault();
      this.classList.add('upload-hover');
    });

    uploadArea.addEventListener('dragleave', function() {
      this.classList.remove('upload-hover');
    });

    uploadArea.addEventListener('drop', function(e) {
      e.preventDefault();
      this.classList.remove('upload-hover');
      
      if (e.dataTransfer.files && e.dataTransfer.files[0]) {
        fileInput.files = e.dataTransfer.files;
        // 触发change事件
        const event = new Event('change');
        fileInput.dispatchEvent(event);
      }
    });

    // 提交按钮点击事件
    submitButton.addEventListener('click', function() {
      // 验证是否已配置API密钥
      if (!COZE_API_KEY || COZE_API_KEY === 'YOUR_COZE_API_KEY') {
        alert('请先在代码中配置您的Coze API密钥');
        return;
      }
      
      // 验证是否选择了文件
      const file = fileInput.files[0];
      if (!file) {
        alert('请选择要上传的图片');
        return;
      }
      
      // 显示加载动画
      loadingOverlay.classList.remove('hidden');
      
      // 更新加载提示文本
      const loadingContainer = loadingOverlay.querySelector('div');
      if (loadingContainer) {
        let loadingText = loadingContainer.querySelector('p');
        if (!loadingText) {
          loadingText = document.createElement('p');
          loadingContainer.appendChild(loadingText);
        }
        loadingText.textContent = '正在上传图片...';
      }
      
      console.log('开始调用Coze API流程...');
      
      // 第一步：调用上传文件接口
      function uploadFile(attempt = 1, maxAttempts = 3) {
        console.log('===== 上传文件接口调用 (尝试', attempt, '/', maxAttempts, ') =====');
        
        // 使用FormData上传文件
        const formData = new FormData();
        formData.append('file', file);
        
        const uploadXhr = new XMLHttpRequest();
        uploadXhr.open('POST', 'https://api.coze.cn/v1/files/upload', true);
        uploadXhr.setRequestHeader('Authorization', 'Bearer ' + COZE_API_KEY);
        
        uploadXhr.onload = function() {
          console.log('上传文件响应状态:', uploadXhr.status);
          console.log('上传文件响应文本:', uploadXhr.responseText);
          
          try {
            const responseData = JSON.parse(uploadXhr.responseText);
            console.log('上传文件响应数据:', responseData);
            
            if (uploadXhr.status === 200 && responseData.code === 0 && responseData.data && responseData.data.id) {
              // 上传成功，获取file_id
              const fileId = responseData.data.id;
              console.log('文件上传成功！获取到file_id:', fileId);
              
              // 更新加载提示
              if (loadingContainer) {
                let loadingText = loadingContainer.querySelector('p');
                if (loadingText) {
                  loadingText.textContent = '文件上传成功，正在执行OCR识别...';
                }
              }
              
              // 第二步：使用file_id调用工作流执行接口
              runWorkflowWithFileId(fileId, 1, 3);
            } else {
              // 上传失败
              const errorMsg = responseData.msg || '上传失败 (状态码: ' + uploadXhr.status + ')';
              console.error('文件上传错误:', errorMsg);
              
              // 检查是否需要重试
              if (attempt < maxAttempts) {
                console.log('上传失败，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
                setTimeout(function() {
                  uploadFile(attempt + 1, maxAttempts);
                }, 1000 * attempt);
              } else {
                // 隐藏加载动画
                loadingOverlay.classList.add('hidden');
                showManualInputOption('文件上传失败: ' + errorMsg);
              }
            }
          } catch (parseError) {
            // JSON解析错误
            console.error('上传响应解析错误:', parseError);
            
            // 检查是否需要重试
            if (attempt < maxAttempts) {
              console.log('解析错误，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
              setTimeout(function() {
                uploadFile(attempt + 1, maxAttempts);
              }, 1000 * attempt);
            } else {
              // 隐藏加载动画
              loadingOverlay.classList.add('hidden');
              showManualInputOption('上传响应解析错误: ' + parseError.message + '\n响应内容: ' + uploadXhr.responseText);
            }
          }
        };
        
        uploadXhr.onerror = function() {
          console.error('上传文件网络错误');
          
          // 检查是否需要重试
          if (attempt < maxAttempts) {
            console.log('网络错误，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
            setTimeout(function() {
              uploadFile(attempt + 1, maxAttempts);
            }, 1000 * attempt);
          } else {
            // 隐藏加载动画
            loadingOverlay.classList.add('hidden');
            showManualInputOption('上传网络连接错误，请检查您的网络连接');
          }
        };
        
        uploadXhr.ontimeout = function() {
          console.error('上传文件请求超时');
          
          // 检查是否需要重试
          if (attempt < maxAttempts) {
            console.log('请求超时，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
            setTimeout(function() {
              uploadFile(attempt + 1, maxAttempts);
            }, 1000 * attempt);
          } else {
            // 隐藏加载动画
            loadingOverlay.classList.add('hidden');
            showManualInputOption('上传请求超时，请稍后重试');
          }
        };
        
        // 设置超时
        uploadXhr.timeout = 30000; // 30秒
        
        // 发送上传请求
        uploadXhr.send(formData);
      }
      
      // 第二步：使用file_id调用工作流执行接口
      function runWorkflowWithFileId(fileId, attempt = 1, maxAttempts = 3) {
        console.log('===== 工作流执行接口调用 (尝试', attempt, '/', maxAttempts, ') =====');
        console.log('使用的file_id:', fileId);
        
        // 根据文档要求：对于Image类型参数，使用file_id格式
        const requestData = {
          workflow_id: '7565359216300736554',
          parameters: {
            // 将file_id包装成JSON字符串格式
            input_image: '{"file_id":"' + fileId + '"}'
          },
          user_id: 'user_' + Date.now() + '_' + attempt
        };
        
        // 使用XHR发送JSON请求
        const workflowXhr = new XMLHttpRequest();
        workflowXhr.open('POST', COZE_WORKFLOW_ENDPOINT, true);
        workflowXhr.setRequestHeader('Authorization', 'Bearer ' + COZE_API_KEY);
        workflowXhr.setRequestHeader('Content-Type', 'application/json');
        
        workflowXhr.onload = function() {
          console.log('工作流响应状态:', workflowXhr.status);
          console.log('工作流响应文本:', workflowXhr.responseText);
          
          try {
            const responseData = JSON.parse(workflowXhr.responseText);
            console.log('工作流响应数据:', responseData);
            
            // 处理响应
            if (workflowXhr.status === 200 && responseData.code === 0) {
              // 隐藏加载动画
              loadingOverlay.classList.add('hidden');
              
              // 成功处理
              let recognizedText = '';
              try {
                const parsedData = typeof responseData.data === 'string' ? 
                  JSON.parse(responseData.data) : responseData.data;
                recognizedText = parsedData.output || JSON.stringify(parsedData);
              } catch (e) {
                recognizedText = responseData.data || JSON.stringify(responseData);
              }
              
              // 过滤只保留汉字
              const filteredChars = recognizedText.replace(/[^一-龥]/g, '');
              console.log('过滤后的汉字:', filteredChars);
              localStorage.setItem('recognizedChars', filteredChars);
              
              // 获取用户性别和年龄信息
              const gender = localStorage.getItem('userGender') || '未知';
              const age = localStorage.getItem('userAge') || '未知';
              
              // 调用分析工作流
              callAnalysisWorkflow(filteredChars, gender, age);
            } else {
              // API返回错误
              const errorMsg = responseData.msg || '未知错误 (状态码: ' + workflowXhr.status + ')';
              console.error('工作流执行错误:', errorMsg);
              
              // 检查是否需要重试
              if (errorMsg.includes('service internal error') && attempt < maxAttempts) {
                console.log('服务内部错误，' + attempt + '秒后第' + (attempt + 1) + '次尝试...');
                // 更新加载提示
                if (loadingContainer) {
                  let loadingText = loadingContainer.querySelector('p');
                  if (loadingText) {
                    loadingText.textContent = '分析中，预计需要2分钟左右...（正在进行第' + (attempt + 1) + '次尝试）';
                  }
                }
                
                // 延迟后重试
                setTimeout(function() {
                  runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
                }, 1000 * attempt);
              } else {
                // 隐藏加载动画
                loadingOverlay.classList.add('hidden');
                showManualInputOption('工作流执行错误: ' + errorMsg);
              }
            }
          } catch (parseError) {
            // JSON解析错误
            console.error('工作流响应解析错误:', parseError);
            
            // 检查是否需要重试
            if (attempt < maxAttempts) {
              console.log('解析错误，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
              setTimeout(function() {
                runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
              }, 1000 * attempt);
            } else {
              // 隐藏加载动画
              loadingOverlay.classList.add('hidden');
              showManualInputOption('工作流响应解析错误: ' + parseError.message + '\n响应内容: ' + workflowXhr.responseText);
            }
          }
      };
      
      workflowXhr.onerror = function() {
        console.error('工作流执行网络错误');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('网络错误，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
          setTimeout(function() {
            runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          // 隐藏加载动画
          loadingOverlay.classList.add('hidden');
          showManualInputOption('工作流执行网络连接错误，请检查您的网络连接');
        }
      };
      
      workflowXhr.ontimeout = function() {
        console.error('工作流执行请求超时');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('请求超时，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
          setTimeout(function() {
            runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          // 隐藏加载动画
          loadingOverlay.classList.add('hidden');
          showManualInputOption('工作流执行请求超时，请稍后重试');
        }
      };
      
      // 设置超时
      workflowXhr.timeout = 30000; // 30秒
      
      workflowXhr.onerror = function() {
        console.error('工作流执行网络错误');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('网络错误，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
          setTimeout(function() {
            runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          // 隐藏加载动画
          loadingOverlay.classList.add('hidden');
          showManualInputOption('工作流执行网络连接错误，请检查您的网络连接');
        }
      };
      
      workflowXhr.ontimeout = function() {
        console.error('工作流执行请求超时');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('请求超时，' + attempt + '秒后第' + (attempt + 1) + '次重试...');
          setTimeout(function() {
            runWorkflowWithFileId(fileId, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          // 隐藏加载动画
          loadingOverlay.classList.add('hidden');
          showManualInputOption('工作流执行请求超时，请稍后重试');
        }
      };
      
      // 发送JSON请求
      workflowXhr.send(JSON.stringify(requestData));
    }
    
    // 分析工作流函数定义 - 直接跳转到结果页面
    function callAnalysisWorkflow(chars, gender, age) {
      console.log('===== 准备分析工作流 =====');
      console.log('识别的汉字:', chars);
      console.log('用户性别:', gender);
      console.log('用户年龄:', age);
      
      // 存储分析所需的信息到localStorage
      localStorage.setItem('charsForAnalysis', chars);
      localStorage.setItem('analysisGender', gender);
      localStorage.setItem('analysisAge', age);
      localStorage.setItem('analysisAttempt', '1');
      localStorage.setItem('maxAnalysisAttempts', '3');
      localStorage.setItem('analysisStatus', 'pending');
      localStorage.removeItem('analysisResult'); // 清除之前的结果
      
      // 立即跳转到结果页面，在结果页面中使用模拟数据
      console.log('立即跳转到分析结果页面...');
      window.location.href = 'analysis-result.html';
    }

              

      
      // 显示手动输入选项的函数
      function showManualInputOption(errorMessage) {
        // 清空之前的内容
        const mainContainer = document.querySelector('.container');
        const existingManualContainer = document.getElementById('manual-input-container');
        if (existingManualContainer) {
          existingManualContainer.remove();
        }
        
        // 创建手动输入容器
        const manualContainer = document.createElement('div');
        manualContainer.id = 'manual-input-container';
        manualContainer.className = 'mt-6 p-6 bg-yellow-50 rounded-lg shadow-lg';
        
        manualContainer.innerHTML = [
          '<h3 class="text-xl font-bold text-red-600 mb-3">识别遇到问题</h3>',
          '<p class="text-gray-700 mb-4">' + errorMessage + '</p>',
          '<div class="mb-4">',
          '  <label for="manual-characters" class="block text-gray-700 font-medium mb-2">请手动输入图片中的手写汉字：</label>',
          '  <textarea id="manual-characters" rows="5" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary" placeholder="请输入识别出的所有汉字，例如：天、地、人、和、平..."></textarea>',
          '</div>',
          '<div class="flex flex-col sm:flex-row gap-3">',
          '  <button id="submit-manual-input" class="flex-1 px-6 py-3 bg-primary text-white font-medium rounded-md hover:btn-hover transition-colors">提交分析</button>',
          '  <button id="retry-ocr" class="flex-1 px-6 py-3 bg-gray-200 text-gray-700 font-medium rounded-md hover:bg-gray-300 transition-colors">重新上传图片</button>',
          '</div>',
          '<p class="text-sm text-gray-500 mt-4">提示：请确保输入的汉字尽可能准确，这将影响分析结果的质量。</p>'
        ].join('');
        
        // 添加到容器
        const submitButton = document.getElementById('submit-button');
        submitButton.parentNode.insertBefore(manualContainer, submitButton.nextSibling);
        
        // 绑定事件处理
        document.getElementById('submit-manual-input').addEventListener('click', function() {
          const manualText = document.getElementById('manual-characters').value.trim();
          if (manualText) {
              const filteredChars = manualText.replace(/[^\u4e00-\u9fa5]/g, '');
              if (filteredChars.length > 0) {
                localStorage.setItem('recognizedChars', filteredChars);
                
                // 获取用户性别和年龄信息
                const gender = localStorage.getItem('userGender') || '未知';
                const age = localStorage.getItem('userAge') || '未知';
                
                // 重新显示加载动画
                const loadingOverlay = document.getElementById('loading-overlay');
                if (loadingOverlay) {
                  loadingOverlay.classList.remove('hidden');
                  const loadingContainer = loadingOverlay.querySelector('div');
                  if (loadingContainer) {
                    let loadingText = loadingContainer.querySelector('p');
                    if (loadingText) {
                      loadingText.textContent = '分析中，预计需要2分钟左右...';
                    }
                  }
                }
                
                // 调用分析工作流
                callAnalysisWorkflow(filteredChars, gender, age);
              } else {
                alert('输入的内容不包含汉字，请重新输入');
              }
          } else {
            alert('请输入识别结果');
          }
        });
        
        document.getElementById('retry-ocr').addEventListener('click', function() {
          manualContainer.remove();
          fileInput.value = '';
          imagePreview.classList.add('hidden');
          submitButton.disabled = true;
        });
      }
      
      // 开始执行上传文件
      uploadFile();
    });
    
    // 手动输入处理函数
    function handleManualInput() {
      // 直接提供手动输入选项，无需用户确认
      const recognizedChars = prompt('请手动输入图片中的汉字：');
      if (recognizedChars && recognizedChars.trim().length > 0) {
        const filteredChars = recognizedChars.replace(/[^\u4e00-\u9fa5]/g, '');
        if (filteredChars.length > 0) {
          localStorage.setItem('recognizedChars', filteredChars);
          
          // 获取用户性别和年龄信息
          const gender = localStorage.getItem('userGender') || '未知';
          const age = localStorage.getItem('userAge') || '未知';
          
          // 显示加载动画
          const loadingOverlay = document.getElementById('loading-overlay');
          if (loadingOverlay) {
            loadingOverlay.classList.remove('hidden');
            const loadingContainer = loadingOverlay.querySelector('div');
            if (loadingContainer) {
              let loadingText = loadingContainer.querySelector('p');
              if (!loadingText) {
                loadingText = document.createElement('p');
                loadingContainer.appendChild(loadingText);
              }
              loadingText.textContent = '分析中，预计需要2分钟左右...';
            }
          }
          
          // 调用分析工作流
          callAnalysisWorkflow(filteredChars, gender, age);
        } else {
          alert('输入的内容不包含汉字，请重新输入');
        }
      }
    }
  </script>
</body>
</html>